/**
 * 网络请求fetch/xhr拦截数据注入组件
 */
import { BatchInterceptor } from "@mswjs/interceptors"
// import { ClientRequestInterceptor } from "@mswjs/interceptors/ClientRequest"
import { FetchInterceptor } from "@mswjs/interceptors/fetch"
import { XMLHttpRequestInterceptor } from "@mswjs/interceptors/XMLHttpRequest"
import type { PlasmoCSConfig, PlasmoGetShadowHostId } from "plasmo"
import React, { useEffect } from "react"

// 注入配置
export const config: PlasmoCSConfig = {
  // 需要注入的网站url
  matches: [
    // 抖音大屏专业版url
    "https://compass.jinritemai.com/screen/live/*",
    // 抖音抖店商铺体验分
    "https://fxg.jinritemai.com/ffa/eco/experience-score*",
    "https://fxg.jinritemai.com/ffa/eco/experience-score/detail*",
    // 快手大屏专业版url
    "https://zs.kwaixiaodian.com/realtime/operating/systemMain*",
    // 快手直播数据大屏(专业新版 2024/09/20)
    "https://zs.kwaixiaodian.com/realtime/operating/zones/dataScreen/main*",
    // 视频号直播数据大屏url
    // "https://channels.weixin.qq.com/platform/statistic/dashboardV4*",
    // 视频号店铺体验分
    "https://store.weixin.qq.com/shop/setting/rate*",
    // 视频号加热订单页面url
    "https://channels.weixin.qq.com/promote/pages/platform/live/home*"
    // 淘宝使用script类型获取，不能拦截
  ],
  world: "MAIN",
  all_frames: true,
  run_at: "document_start"
}

// 注入的shadow dom的id
export const HOST_ID = "hijack-injected-func"
export const getShadowHostId: PlasmoGetShadowHostId = () => HOST_ID

const HijackInjected: React.FC = () => {
  const interceptor = new BatchInterceptor({
    name: "my-interceptor",
    interceptors: [
      // new ClientRequestInterceptor(),
      new XMLHttpRequestInterceptor(),
      new FetchInterceptor()
    ]
  })

  // 处理GET请求
  function handleGetRequest(request: Request) {
    const url = new URL(request.url)
    return Object.fromEntries(url.searchParams.entries())
  }

  // 处理POST、PUT、DELETE等请求
  async function handleOtherRequests(request: Request) {
    try {
      return await request.clone().json()
    } catch (error) {
      // console.log(await request.clone())
      // console.error("无法解析请求体:", error)
      return {}
    }
  }

  interceptor.on("response", async ({ response, request }) => {
    // 获取请求标头
    let headers = {}
    try {
      headers = Object.fromEntries(request.headers.entries())
    } catch (e) {
      headers = {}
    }
    // 请求参数获取
    let params = {}
    if (request.method === "GET") {
      params = handleGetRequest(request)
    } else {
      params = await handleOtherRequests(request)
    }
    // 拦截结果
    const interceptorData = {
      url: request.url,
      params: params,
      method: request.method,
      headers: headers,
      response: {}
    }

    try {
      interceptorData.response = await response.clone().json()
    } catch (e) {
      interceptorData.response = await response.text()
    }

    // 测试-打印请求
    // console.log("请求拦截数据：", interceptorData)

    // 触发自定义事件
    window.dispatchEvent(
      new CustomEvent("hijackEvent", {
        detail: interceptorData
      })
    )

    // 检查是否有parent，如果有，则向parent发送数据
    if (window.parent) {
      window.parent.dispatchEvent(
        new CustomEvent("hijackEvent", {
          detail: interceptorData
        })
      )
    }
  })

  useEffect(() => {
    interceptor.apply()
  }, [])

  return <div>{/*挂载一个空的div*/}</div>
}

export default HijackInjected
